/**
 * Created by Tazyong on 2017/5/17.
 */

export default (function () {

  /****************** 信息窗内容模板 ******************/
  let contentTemplate =
    '<div class="info-title">{{placeName}}</div>' +
    '<div class="info-content">' +
      '<p>' +
        '<span>地　址：</span>' +
        '<span>{{placeAddress}}</span>' +
      '</p>' +
      '<p>' +
        '<span>电　话：</span>' +
        '<span>{{placeMobile}}</span>' +
      '</p>' +
      '<p>' +
        '<span>联系人：</span>' +
        '<span>{{placeContact}}</span>' +
      '</p>' +
    '</div>';

  /****************** 显示地图 ******************/
  function showMap(element, placeInfo) {
    let content = contentTemplate.replace('{{placeName}}', placeInfo.shop_name)
      .replace('{{placeAddress}}', placeInfo.address)
      .replace('{{placeMobile}}', placeInfo.mobile.split(',')[0])
      .replace('{{placeContact}}', placeInfo.contact1);

    AMap.plugin('AMap.AdvancedInfoWindow', function () {
      let map = new AMap.Map(element,{
          zoom: 14,
          center: [placeInfo.JD, placeInfo.WD + 0.009]
        }),
        marker = new AMap.Marker({
          position: [placeInfo.JD, placeInfo.WD]
        }),
        infowindow = new AMap.AdvancedInfoWindow({
          content: content,
          offset: new AMap.Pixel(0, -36),
          closeWhenClickMap: true,
          walking: false
        });
      marker.setMap(map);
      marker.on('click', function () {
        infowindow.open(map, [placeInfo.JD, placeInfo.WD]);
      });
      infowindow.open(map, [placeInfo.JD, placeInfo.WD]);
    });
  }

  /****************** 定位当前位置信息 ******************/
  function getPosition(onComplete, onError) {
    AMap.plugin('AMap.Geolocation', function(){
      let geolocation = new AMap.Geolocation({
        timeout: 10000
      });
      geolocation.getCurrentPosition();
      AMap.event.addListener(geolocation, 'complete', function (data) {
        typeof onComplete === 'function'
          ? onComplete([data.position.getLng(), data.position.getLat()]) : '';
      });
      AMap.event.addListener(geolocation, 'error', function () {
        typeof onError === 'function' ? onError() : '';
      });
    });
  }

  /****************** 查找最近位置并显示地图 ******************/
  function latestPlace(element, placesInfo) {
    getPosition(function (position) {
      let pos = new AMap.LngLat(position[0], position[1]);
      placesInfo.sort(function (a, b) {
        return pos.distance([a.JD, a.WD]) - pos.distance([b.JD, b.WD]);
      });
      showMap(element, placesInfo[0]);
    });
  }

  /****************** 返回对象构造方法 ******************/
  return {
    showMap,
    latestPlace,
    getPosition
  }
})();
